const imgLoad = (imgList = [], progressCb, completeCb) => {

  let len = imgList.length;
  let num = 0;
  let progress = 0;
  var loadImage = function (src) {
    return new Promise(function (resolve, reject) {
      let img = new Image();
      img.onload = function () {
        resolve(img); //加载时执行resolve函数
      };
      img.onerror = function () {
        reject('地址错误:' + src); //抛出异常时执行reject函数
      };
      img.src = src;
    });
  };

  function* fn() {
    for (let i = 0; i < len; i++) {
      yield loadImage(imgList[i]);
    }
  }

  let g = fn();
  let value = g.next().value;
  resume();

  function resume() {
    console.log('====')
    value.then((img) => {
      // 单张加载完成
      num++;
      progress = parseFloat((100 / len) * num).toFixed(2);
      progressCb && progressCb(img, progress);
      value = g.next().value;
      if (value) {
        resume();
      } else {
        // 全部加载完成
        completeCb && completeCb();
      }
    }).catch((err)=>{
      console.log(err)
    });
  }
}
class Log {
  TAG = 'YGLog: ';
  timeList = [];
  constructor(opt){
    this.opt = opt || '';
  }
  log(...str){
    console.log(this.joinStr(str))
  }
  info(...str){
    console.info(this.joinStr(str))
  }
  warn(...str){
    console.warn(this.joinStr(str))
  }
  debug(...str){
    console.debug(this.joinStr(str))
  }
  error(...str){
    console.error(this.joinStr(str))
  }
  joinStr(str){
    str.map((item,index) => {
      if(typeof item == 'object'){
        str[index] = JSON.stringify(item)
      }
    })
    return this.opt + ' ' + this.TAG + str.join(' ');
  }
  time(params) {
    let arr = this.timeList;
    let index = this.findElem(arr, 'name', params);
    if(index == -1){
      arr.push({
        name: params,
        start: new Date().getTime()
      })
    }
  }
  timeEnd(params) {
    let index = this.findElem(this.timeList, 'name', params);
    if(index > -1){
      let endT = new Date().getTime();
      let startT = this.timeList[index].start;
      this.log(`${params} 耗时： ${endT - startT} ms`);
      this.timeList.splice(index,1)
    }
  }

  /**
  * array 要查找的源数组
  * attr 需要查找数组里对象的某个属性值
  * val 需要匹配的值
  */
  findElem(array, attr, val) {
    for (var i = 0; i < array.length; i++) {
      if (array[i][attr] == val) {
        return i; //返回当前索引值
      }
    }
    return -1;
  };
}

export { imgLoad, Log }